package com.xunmall.web.service.impl;

import com.google.common.collect.Sets;
import com.xunmall.base.dto.Result;
import com.xunmall.security.SecUser;
import com.xunmall.web.entity.RoleDO;
import com.xunmall.web.entity.UserDO;
import com.xunmall.web.service.RoleService;
import com.xunmall.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    //登录验证
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result result = userService.getByLoginName(username);
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户" + username + " 不存在");
        }
        UserDO userDO = (UserDO) result.getData();
        Collection<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(userDO.getUuid());
        boolean enabled = userDO.getStatus() == 1 ? true : false;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = enabled;

        SecUser userdetails = new SecUser(userDO.getUuid(), userDO.getLoginName(), userDO.getPassword(), userDO.getSalt(), userDO.getUserName(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

        return userdetails;
    }

    /**
     * 获得用户所有角色的权限集合.
     */
    private Collection<GrantedAuthority> obtainGrantedAuthorities(String userId) {
        Collection<GrantedAuthority> authSet = Sets.newHashSet();
        List<RoleDO> roles = roleService.getRoleListByUserId(userId);
        for (RoleDO role : roles) {
            authSet.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return authSet;
    }
}

